package com.dqhl.community.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.dqhl.community.R;
import com.dqhl.community.activity.DistributionDetailActivity;
import com.dqhl.community.activity.OrderSingleActivity;
import com.dqhl.community.adapter.OrderListAdapter;
import com.dqhl.community.adapter.OrderLvAdapter;
import com.dqhl.community.base.BaseFragment;
import com.dqhl.community.model.OrderRecord;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LIENLIN on 2016/8/31.
 * 订单-未到达
 */
public class OrderUnFinishFragment extends BaseFragment {

    private ListView mLvOrder;
    private TextView tv_no_info;
    private List<OrderRecord> orderRecordList; //所有订单list
    private List<OrderRecord> unFinishOrderList; //未完成订单list
    //    private OrderLvAdapter orderLvAdapter;
    private OrderListAdapter orderListAdapter;
    private PtrClassicFrameLayout ptr_list;
    Handler handler = new Handler();
    //分页
    int page = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        mLvOrder = (ListView) view.findViewById(R.id.lv_fragment_order);
        tv_no_info = (TextView) view.findViewById(R.id.tv_no_info);
        ptr_list = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_list);
    }

    private void initData() {
        //下拉刷新
        ptr_list.postDelayed(new Runnable() {

            @Override
            public void run() {
                ptr_list.autoRefresh(true);
                ptr_list.setLoadMoreEnable(true);
            }
        }, 150);

        ptr_list.setPtrHandler(new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
//                        unFinishOrderList.clear();
                        //获取数据
                        getData();
                        ptr_list.refreshComplete();
                        ptr_list.setLoadMoreEnable(true);
                    }
                }, 1000);
            }
        });

        ptr_list.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        ptr_list.loadMoreComplete(true);
                        page++;
                        Dlog.e("GGpages" + page);
                        loadMoreData();

                    }
                }, 1000);
            }
        });

        // ViewPager滑动冲突
        ptr_list.disableWhenHorizontalMove(false);

    }

    private void getData() {
        Dlog.e(user.getUserid() + ";" + page + ";1");
        showCustomLoadBar("加载中……");
        RequestParams params = new RequestParams(Config.Api.supermarketOrder);
        params.addBodyParameter("userid", user.getUserid());
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("state", "1");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG订单返回数据" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    orderRecordList = JSONArray.parseArray(data, OrderRecord.class);
                    Dlog.e("GG原orderRecordList:" + orderRecordList);
                    unFinishOrderList = new ArrayList<>();
                    for (OrderRecord orderRecord : orderRecordList) {
                        switch (orderRecord.getStatus()) {
                            case "1":
                            case "2":
                            case "3":
                            case "4":
                            case "5":
                            case "6":
                            case "7":
                            case "10":
                                unFinishOrderList.add(orderRecord);
                                break;
                        }
                    }
                    Dlog.e("unFinishOrderList：" + unFinishOrderList);

                    if (unFinishOrderList.size() <= 0) {
                        ptr_list.setVisibility(View.GONE);
                        mLvOrder.setVisibility(View.GONE);
                        tv_no_info.setVisibility(View.VISIBLE);
                        tv_no_info.setText(R.string.error_no_info);
                    } else {
                        ptr_list.setVisibility(View.VISIBLE);
                        mLvOrder.setVisibility(View.VISIBLE);
                        tv_no_info.setVisibility(View.GONE);
                        tv_no_info.setText(R.string.error_no_info);

                        orderListAdapter = new OrderListAdapter(getContext(), unFinishOrderList);
                        mLvOrder.setAdapter(orderListAdapter);
                        mLvOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("order", unFinishOrderList.get(position));
                                overlay(OrderSingleActivity.class, bundle);
                            }
                        });

                    }

                } else {
                    ptr_list.setVisibility(View.GONE);
                    mLvOrder.setVisibility(View.GONE);
                    tv_no_info.setVisibility(View.VISIBLE);
                    tv_no_info.setText(R.string.error_server_connection);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ptr_list.setVisibility(View.GONE);
                mLvOrder.setVisibility(View.GONE);
                tv_no_info.setVisibility(View.VISIBLE);
                tv_no_info.setText(R.string.error_net_connection);
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void loadMoreData() {
        showCustomLoadBar("加载中……");
        RequestParams params = new RequestParams(Config.Api.supermarketOrder);
        params.addBodyParameter("userid", app.getUserId());
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("state", "1");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("GG订单返回数据" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    List<OrderRecord> moreOrderRecordList = new ArrayList<OrderRecord>(JSONArray.parseArray(data, OrderRecord.class));
                    Dlog.e("jiazai原orderRecordList:" + moreOrderRecordList);
                    List<OrderRecord> moreUnFinishOrderList = new ArrayList<OrderRecord>();
                    for (OrderRecord orderRecord : moreOrderRecordList) {
                        switch (orderRecord.getStatus()) {
                            case "1":
                            case "2":
                            case "3":
                            case "4":
                            case "5":
                            case "6":
                            case "7":
                            case "10":
                                moreUnFinishOrderList.add(orderRecord);
                                break;
                        }
                    }
                    Dlog.e("moreUnFinishOrderList：" + moreUnFinishOrderList);

                    ptr_list.setVisibility(View.VISIBLE);
                    mLvOrder.setVisibility(View.VISIBLE);
                    tv_no_info.setVisibility(View.GONE);
//                        orderLvAdapter = new OrderLvAdapter(getContext(),
//                                R.layout.lv_fragment_unorder_item, unFinishOrderList);
//                        mLvOrder.setAdapter(orderLvAdapter);
                    //TODO
                    unFinishOrderList.addAll(moreUnFinishOrderList);
                    orderListAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

}
